/*
 * geliframe.cpp
 *
 *  Created on: 2011-10-7
 *  Author    : gelif(admin@gelif.net)
 */
#include "geliframe.h"
#include <wx/file.h>
#include <wx/textfile.h>
#include <wx/stopwatch.h>
#define TOP true
#define BOTTOM false
////Event Table Start
BEGIN_EVENT_TABLE(GeliFrame, wxFrame) EVT_CLOSE(GeliFrame::onClose)
    EVT_TIMER(ID_TIMERDRAW, GeliFrame::timerDrawTimer)
    EVT_BUTTON(ID_BUTTONDISCONNECT, GeliFrame::buttonDisconnectClick)
    EVT_BUTTON(ID_BUTTONHOST, GeliFrame::buttonHostClick)
    EVT_BUTTON(ID_BUTTONJOIN, GeliFrame::buttonJoinClick)
END_EVENT_TABLE()
////Event Table End

//----------------------------------------------------------------------------
// GeliFrame
//----------------------------------------------------------------------------
GeliFrame::GeliFrame(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position,
        const wxSize& size)
        : wxFrame(parent, id, title, position, size, GELIFRAME_STYLE)
{
    createGUIControls();
    this->game = new Game;
    //this->game->move(Coordinate(11, 9), Coordinate::BLACK);
    hostjoinDialog = new HostJoinDialog(this);

    // connect the hotkeys
    boardGLCanvas = new GelifGLCanvas(this, panelBoard, ID_PANELBOARD, wxDefaultPosition, panelBoard->GetSize());
    boardGLCanvas->Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(GelifGLCanvas::onKeyDown));
    boardGLCanvas->SetFocus();
    // set some defaults
    client = NULL;
    server = NULL;

    // set the colors
    boardGLCanvas->setDefaultColors();
}

GeliFrame::~GeliFrame()
{
    //options->Hide();
    //options->Destroy();
}

void GeliFrame::onClose(wxCloseEvent& WXUNUSED(event))
{
    //delete board;
    //board = NULL;

    if (client != NULL)
    {
        wxCommandEvent e;
        buttonDisconnectClick(e);
    }
    if (server != NULL)
    {
        shutdownServer();
    }
    this->Destroy();
}

void GeliFrame::buttonHostClick(wxCommandEvent& WXUNUSED(event))
{
    // get the hosting info (address is not necessary for hosting)
    hostjoinDialog->editAddress->Disable();
    if (!hostjoinDialog->ShowModal())
    {
        return;
    }

    // delete the old server object and create a new one
    if (server != NULL)
    {
        wxDELETE(server);
    }
    server = new TCPServer(this);

    // actually start hosting!
    if (server->Create(hostjoinDialog->editPort->GetValue()))
    {
        this->game->mypiece = Coordinate::BLACK;
        this->game->status = Game::IS_WAITING;
        // add the first element of the people list (you)
        //listServer->Clear();
        //listServer->Append(hostjoinDialog->editName->GetValue(), (wxClientData *)new TCPClientData(this, 0));
        // disable the appropriate buttons
        disableConnect();
    }
    else
    {
        //throw "server == null";
        wxDELETE(server);
        enableConnect();
    }
}

void GeliFrame::buttonJoinClick(wxCommandEvent& WXUNUSED(event))
{
    hostjoinDialog->editAddress->Enable(); // we need all the fields for joining!
    if (!hostjoinDialog->ShowModal())
    {
        return;
    }

    if (client != NULL)
    {
        wxDELETE(client);
    }
    client = new TCPClient(this);

    disableConnect();

    if (client->connect(hostjoinDialog->editAddress->GetValue(), hostjoinDialog->editPort->GetValue(), wxT("gelifconnect")))
    {
        this->game->mypiece = Coordinate::WHITE;
        this->game->status = Game::IS_ON;
        //client->connection->Poke(wxT("name"), hostjoinDialog->editName->GetValue().wchar_str());
    }
    else
    {
        //throw "cannot connect server!";
        wxDELETE(client);
        enableConnect();
    }
}

void GeliFrame::enableConnect()
{
    client = NULL;
    server = NULL;
    buttonJoin->Enable();
    buttonHost->Enable();
    hostjoinDialog->editAddress->Enable();
    hostjoinDialog->editPort->Enable();
    //listServer->Disable();
    buttonDisconnect->Disable();
}

void GeliFrame::disableConnect()
{
    buttonJoin->Disable();
    buttonHost->Disable();
    hostjoinDialog->editAddress->Disable();
    hostjoinDialog->editPort->Disable();
    //listServer->Enable();
    buttonDisconnect->Enable();
}

void GeliFrame::updateEverybody()
{
    // update the server/clients
    //TODO
}

void GeliFrame::timerDrawTimer(wxTimerEvent& WXUNUSED(event))
{
    boardGLCanvas->draw();
}

void GeliFrame::clearServerList()
{
    //listServer->Clear();
}

void GeliFrame::buttonDisconnectClick(wxCommandEvent& WXUNUSED(event))
{
    if (client != NULL) // if you're a client, just disconnect!
    {
        //Disconnecting client, deleting resources
        wxDELETE(client); // this disconnects too
        // now we have to delete all the entries in the user list
        //clearServerList();
        enableConnect();
    }
    else if (server != NULL) // if you're a server, disconnect the selected client or shut it down
    {
        // shut down the server!
        shutdownServer();
    }
    this->game->initStatus();
}

void GeliFrame::shutdownServer()
{
    if (server != NULL)
    {
        // disconnect everything and clean up
        //server->PokeEveryone(wxT("chat"), wxT("Server is shutting down!"), -1, wxIPC_TEXT);
        server->disconnect();
        wxDELETE(server);
        enableConnect();
    }
}

void GeliFrame::poke(const wxString &item, wxChar *data, int size, wxIPCFormat format)
{
    if (client != NULL)
    {
        client->pokeServer(item, data, size, format);
    }
    else if (server != NULL)
    {
        server->pokeClient(item, data, size, format);
    }
}

void GeliFrame::createGUIControls()
{
    //Do not add custom code between
    //GUI Items Creation Start and GUI Items Creation End
    //wxDev-C++ designer will remove them.
    //Add the custom code before or after the blocks
    ////GUI Items Creation Start

    panelBackground = new wxPanel(this, ID_PANELBACKGROUND, wxPoint(0, 0), wxSize(746, 556));
    panelBackground->SetBackgroundColour(wxColour(244, 244, 244));

    panelBoard = new wxPanel(panelBackground, ID_PANELBOARD, wxPoint(20, 14), wxSize(521, 507), wxWANTS_CHARS);

    buttonJoin = new wxButton(panelBackground, ID_BUTTONJOIN, wxT("Join"), wxPoint(570, 46), wxSize(65, 28), 0,
            wxDefaultValidator, wxT("buttonJoin"));

    buttonHost = new wxButton(panelBackground, ID_BUTTONHOST, wxT("Host"), wxPoint(655, 46), wxSize(65, 28), 0,
            wxDefaultValidator, wxT("buttonHost"));

/*
    wxArrayString arrayString_listServer;
    listServer = new wxListBox(panelBackground, ID_LISTPEOPLE, wxPoint(570, 81), wxSize(137, 223),
            arrayString_listServer, wxLB_SINGLE);
    listServer->Disable();
*/
    buttonDisconnect = new wxButton(panelBackground, ID_BUTTONDISCONNECT, wxT("disconnect"), wxPoint(570, 318),
            wxSize(137, 28), 0, wxDefaultValidator, wxT("buttonDisconnect"));
    buttonDisconnect->Enable(false);

    wxStaticText1 = new wxStaticText(panelBackground, ID_WXSTATICTEXT5, wxT("Network ______________"), wxPoint(570, 17),
            wxDefaultSize, 0, wxT("WxStaticText5"));
    wxStaticText1->SetForegroundColour(wxColour(192, 192, 192));
    wxStaticText1->SetFont(wxFont(16, wxSWISS, wxNORMAL, wxBOLD, true, wxT("Tahoma")));

    timerDraw = new wxTimer();
    timerDraw->SetOwner(this, ID_TIMERDRAW);
    timerDraw->Start(10);
    SetTitle(wxT("gelifive"));
    SetIcon(wxNullIcon);
    SetSize(8, 8, 754, 584);
    Center();
    this->Show(true);
    ////GUI Items Creation End
}
